package org.dromara.company.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotNull;
import lombok.RequiredArgsConstructor;
import org.dromara.admin.domain.Product;
import org.dromara.admin.domain.bo.ProductBo;
import org.dromara.admin.domain.vo.ProductImportVo;
import org.dromara.admin.domain.vo.ProductVo;
import org.dromara.admin.service.IProductService;
import org.dromara.common.core.domain.R;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.validate.AddGroup;
import org.dromara.common.core.validate.EditGroup;
import org.dromara.common.excel.core.ExcelResult;
import org.dromara.common.excel.utils.ExcelUtil;
import org.dromara.common.idempotent.annotation.RepeatSubmit;
import org.dromara.common.log.annotation.Log;
import org.dromara.common.log.enums.BusinessType;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.common.web.core.BaseController;
import org.dromara.system.listener.SysUserImportListener;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;

/**
 * 公司端产品信息
 *
 * @author Lion Li
 * @date 2025-10-10
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/company/product")
public class ProductController extends BaseController {

    private final IProductService productService;

    /**
     * 查询我的公司产品信息列表
     */
//    @SaCheckPermission("system:product:list")
    @GetMapping("/myList")
    public TableDataInfo<ProductVo> myList(ProductBo bo, PageQuery pageQuery) {
        Long userId = LoginHelper.getUserId();
        if (userId == null) {
            throw new ServiceException("请先登录！");
        }
        bo.setCompanyId(userId);
        return productService.queryPageMyList(bo, pageQuery);
    }

    /**
     * 导出产品信息列表
     */
//    @SaCheckPermission("system:product:export")
    @Log(title = "产品信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(ProductBo bo, HttpServletResponse response) {
        List<ProductVo> list = productService.queryList(bo);
        ExcelUtil.exportExcel(list, "产品信息", ProductVo.class, response);
    }

    /**
     * 导入产品数据
     *
     * @param file 导入文件
     */
//    @SaCheckPermission("system:product:import")
    @Log(title = "产品管理", businessType = BusinessType.IMPORT)
    @PostMapping(value = "/importData", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public R<Void> importData(@RequestPart("file") MultipartFile file) throws Exception {
        ExcelResult<ProductImportVo> result = ExcelUtil.importExcel(file.getInputStream(), ProductImportVo.class, true);
        List<Product> list = MapstructUtils.convert(result.getList(), Product.class);
        Long userId = LoginHelper.getUserId();
        productService.saveBatch(list, userId);
        return R.ok(result.getAnalysis());
    }

    /**
     * 获取产品导入模板
     */
    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) {
        ExcelUtil.exportExcel(new ArrayList<>(), "产品数据模版", ProductImportVo.class, response);
    }

    /**
     * 获取产品信息详细信息
     *
     * @param id 主键
     */
//    @SaCheckPermission("system:product:query")
    @GetMapping("/{id}")
    public R<ProductVo> getInfo(@NotNull(message = "主键不能为空")
                                @PathVariable Long id) {
        return R.ok(productService.queryById(id));
    }

    /**
     * 新增产品信息
     */
//    @SaCheckPermission("system:product:add")
    @Log(title = "产品信息", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    public R<Void> add(@Validated(AddGroup.class) @RequestBody ProductBo bo) {
        Long userId = LoginHelper.getUserId();
        if (userId == null) {
            throw new ServiceException("请先登录！");
        }
        bo.setCreatorId(userId);
        return toAjax(productService.insertByBo(bo));
    }

    /**
     * 修改产品信息
     */
//    @SaCheckPermission("system:product:edit")
    @Log(title = "产品信息", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody ProductBo bo) {
        return toAjax(productService.updateByBo(bo));
    }

    /**
     * 删除产品信息
     *
     * @param ids 主键串
     */
//    @SaCheckPermission("system:product:remove")
    @Log(title = "产品信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")
                          @PathVariable Long[] ids) {
        return toAjax(productService.deleteWithValidByIds(List.of(ids), true));
    }
}
